import { DownOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Dropdown, Menu,message,Col,Row,Table, Tooltip, Tabs,Divider, Card, Switch,Input } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef ,useEffect} from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import DataForm from './components/DataForm';
import { TableListItem } from './data.d';
import router from "umi/router";
import { queryRule, updateRule, addRule, removeRule,updateRankRule } from './service';
import Styles from './index.less';
import { selectEnum } from '@/utils/utils';
import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import { FormValueType } from '@/pages/crm/depart/components/UpdateForm';
import * as TsxHelper from '@/helpers/TsxHelper';
import { EditableFormRow, EditableCell } from './components/BDEditable';
interface TableListProps extends FormComponentProps { }
const { TabPane } = Tabs;

const TableList: React.FC<TableListProps> = props => {
    // 初始化变量区
    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({ common: {} });
    const [type, setType] = useState<any>(7);
    const [nameList, setnameList] = useState<any>([]);
    // 是否更新 关键变量
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    // 表单可见 关键变量
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    // 图片预览
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    // 选中的记录
    const [rowKeys, setRowKeys] = useState<string[] | number[]>([]);

    const actionRef = useRef<ActionType>();

    const handleName = (val) => {
        setnameList(val)
    }
    const [langList, setLangList] = useState<any>([]);
      const [common, setCommon] = useState<any>({});
    useEffect(()=>{
        getTableData({});
    },[])
    // 列定义
    const columns = [
        {
            title: formatMessage({ id: 'app.base.display_order' }),
            dataIndex: 'rank_num',
            width:200,
            editable: true,
        },
        {
            title: formatMessage({ id: 'app.base.associated_plug-in' }),
            dataIndex: 'plug_name',
        },
        {
            title: formatMessage({ id: 'app.base.display_name' }),
            dataIndex: 'name',
            hideInSearch: true,
        },
        {
            title: (
                <>
                    {formatMessage({ id: 'app.base.user_roles_authorized_to_use' })}
                    <Tooltip placement="top" title={common?.roleUsersTips}>
                        <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                    </Tooltip>
                </>
            ),
            dataIndex: 'roleNames',
            hideInSearch: true,
        },
        {
            title: formatMessage({ id: 'app.base.custom_parameters' }),
            dataIndex: 'parameter',
            hideInSearch: true,
        },
        {
            title: formatMessage({ id: 'app.base.enabled_state' }),
            dataIndex: '',
            render: (_, record) => (
                <Switch checked={record.is_enable} onChange={async () => {
                    let s = await handleUpdateItem({ id: record.id, is_enable: (!record.is_enable).toString() });
                    s && getTableData({});
                }} />
            )
        },
        {
            title: formatMessage({ id: 'app.base.option' }),
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <a
                        onClick={() => {
                            handleDataModalVisible(true);
                            setDataFormValues(record);
                            setIsUpdate(true);
                            handleName(record.nameArr)
                        }}
                    >
                        {formatMessage({ id: 'app.base.set_up' })}
                    </a>
                    <Divider type="vertical"></Divider>
                    <a
                    onClick={async e => {
                        TsxHelper.showDeleteConfirm(
                            'danger',
                            handleRemove,
                            record.id,
                            () => {
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }
                            }
                        )
                    }}
                >
                    {formatMessage({ id: 'app.base.delete' })}
                </a>
                </>
            ),
        },
    ];
    const handleSave = (row:any) => {
        const newData = [...langList];
        const index = newData.findIndex(item => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        // this.setState({ dataSource: newData });
        setLangList(newData);
    };
    const newcolumns = columns.map(col => {
        if (!col.editable) {
          return col;
        }
        return {
          ...col,
          onCell: record => ({
            record,
            editable: col.editable,
            dataIndex: col.dataIndex,
            title: col.title,
            handleSave: (row: any) => handleSave(row),
          }),
        };
      });
      
    // 请求接口数据, 设置组件状态
    const getTableData = (params: any) => {
        params.type = type;
        console.log(4566)
        queryRule(params).then((res:any) => {
            if(res.code == 0){
                setCommon(res.data.common)
                if(res.data.list && res.data.list.length>0){
                    setLangList(res.data.list);
                    console.log(res.data.list,545);
                    const listData = {
                      data: res.data.list
                    }
                    return listData
                }else{
                    return []
                }
            }else{
                message.error(res.message);
            }
            
            
        })
    }
    const callback = (key) => {
        console.log(key);
        setType(key)
        //getTableData({type:key})
    }
    const updateRankNum = () => {
        let arr:any = [];
        if(langList.length>0){
            langList.map((item,index)=>{
                arr[index]={
                    'id': item.id,
                    'rank_num': item.rank_num,
                }
            })
        }
        
        let more_json = JSON.stringify(arr);
        console.log(more_json);
        updateRankRule({more_json: more_json}).then(res=>{
            if(res.code == 0){
                message.success('更新成功！')
                getTableData({});
            }else{
                message.error(res.msg)
            }        
        })
    }
    // 表单提交
    const handleSubmitDataForm = (value: any) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then(status => {
            console.log("handleSubmitDataForm status is ", status)
            if (status) {
                handleDataModalVisible(false)
                setIsUpdate(false)
                setDataFormValues({})
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }


    return (<PageHeaderWrapper
            content={'该扩展配置将呈现在「用户中心」的“我的”页面中，例如「钱包」扩展可以让用户中心多一个钱包入口，点击后进入对应的插件功能。'}
        >
            <>
        
        <Row style={{backgroundColor: "#fff",padding:"15px 25px",marginBottom:10,}}>
                <Col style={{display: "flex",justifyContent:"space-between",alignItems:"center"}}>
                    <Button type="primary" onClick={()=>{updateRankNum();}}>更新排序</Button>
                    <Button type="primary" onClick={()=>{setIsUpdate(false);setnameList(common.multilingualoption); handleDataModalVisible(true);}}>新建</Button>
                </Col>    
            </Row>
        <Table 
                style={{backgroundColor: "#fff"}}
                components={{
                    body: {
                      row: EditableFormRow,
                      cell: EditableCell,
                    },
                }}
                rowClassName={() => 'editable-row'}
                columns={newcolumns}
                dataSource={langList}
                pagination={false}
            /></>

            <DataForm
                dataModalVisible={dataModalVisible}
                isUpdate={isUpdate}
                dataFormValues={dataFormValues}
                common={common || {}}
                selectType={type}
                handleName={handleName}
                nameList={nameList}
                onSubmit={async formValue => handleSubmitDataForm(formValue)}
                onCancel={() => handleDataModalVisible(false)}
            />
            {
                previewModelVisible && (
                    <PreviewForm
                        previewModelVisible={previewModelVisible}
                        onVisibleModel={handlePreviewModalVisible}
                        previewImg={previewImg}
                    />
                )
            }
        </PageHeaderWrapper>
    );
};

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: addRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.store-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: FormValueType) => {
    return RequestHelper.bdExec({
        fn: updateRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.update-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

// @ts-ignore
/**
 *  删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
    if (!selectedRows) return true;
    const ids: any = selectedRows;
    return RequestHelper.bdExec({
        fn: removeRule,
        args: { ids },
        successMsg: formatMessage({ id: 'app.base.destroy-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
        hasLoading: false
    });
};

const handleUpdateItem = async (fields: FormValueType) => {
    return RequestHelper.bdExec({ fn: updateRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};
export default Form.create<TableListProps>()(TableList);
